package com.cqc.manage.util.thrift;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

import java.net.Socket;
import java.util.List;
import java.util.Map;

public class TTSocket {
    //thrift socket对象
    private TSocket tSocket;

    // 传输对象
    private TTransport tTransport;

    // 协议对象
    private TProtocol tProtocol;

    // 服务客户端对象
    private getBusiness.Client client;

    /**
     * 构造方法初始化各个连接对象
     *
     * @param host server的地址
     * @param port server的端口
     */
    public TTSocket(String host, Integer port) throws TException {
        tTransport = new TSocket(host, port);
        tTransport.open();
//        tTransport = new TFramedTransport(tSocket, 600);
        //协议对象 这里使用协议对象需要和服务器的一致
        tProtocol = new TBinaryProtocol(tTransport);
        client = new getBusiness.Client(tProtocol);
//
//        TTransport transport = new TSocket("127.0.0.1", 9190);
//            transport.open();
//            TProtocol protocol = new TBinaryProtocol(transport);
//            getBusiness.Client client = new getBusiness.Client(protocol);
////            TestService.Client client = new TestService.Client(protocol);
//
//            //接口调用
//            List<Map<String, String>> businessList = client.getBusinessList();

    }

    /**
     * 获取服务客户端对象
     *
     * @return
     */
    public getBusiness.Client getService() {
        return client;
    }

    /**
     * 打开通道
     *
     * @throws TTransportException
     */
    public void open() throws TTransportException {
        if (null != tTransport && !tTransport.isOpen())
            tTransport.open();
    }

    /**
     * 关闭通道
     */
    public void close() {
        if (null != tTransport && tTransport.isOpen())
            tTransport.close();
    }

    /**
     * 判断通道是否是正常打开状态
     *
     * @return
     */
    public boolean isOpen() {
        Socket socket = tSocket.getSocket();
        if (socket.isConnected() && !socket.isClosed())
            return true;
        return false;
    }
}
